/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

import React, { Component } from "react";
import { connect } from "dva";
import { Button, Form, DatePicker, message, Select, Spin, Popconfirm } from "antd";
import moment from "moment";
import StandardSelect, { Yzs } from "@/components/Select";
import AddressCascader from "@/components/AddressCascader";
import { isEqual } from "lodash";

const FormItem = Form.Item;
const { RangePicker } = DatePicker;
const { Option } = Select;
const dateFormat = "YYYY-MM-DD";
const inoutTypes = [
  {
    code: "in",
    name: "入库件",
  },
  {
    code: "out",
    name: "出库件",
  },
  {
    code: "back",
    name: "退回件",
  },
  {
    code: "delay",
    name: "滞留件",
  },
];
@connect(({ loading, list, report, user }) => ({
  list,
  report,
  shop_id: user.currentUser.shop_id,
  userInfo: user.currentUser.user_info,
  submitting: loading.effects["report/getExportTask"],
  operatoring: loading.effects["list/getBrandsList"],
  yzListing: loading.effects["report/getYzList"],
}))
@Form.create()
class TemplateAdd extends Component {
  state = {
    branch: [],
    bracnhId: [],
    reqYzPayload: {},
    isZyAccount: false,
    codeArr: [],
  };

  componentDidMount() {
    const { userInfo, dispatch } = this.props;
    const { branch = [], branchLevel, user_type } = userInfo;
    const isZyAccount = user_type == "2";
    let ini_branchId;
    let init_branch;
    let reqYzPayload = {};
    let kbCode = [];
    if (branchLevel == 0 && branch.length == 0 && isZyAccount) {
      init_branch = [
        {
          id: "0",
          name: "中国邮政集团有限公司",
          level: "0",
          pid: "-2", // 自定义pid用来区分是否是单独属于总公司账号
        },
      ];
      ini_branchId = ["0", "334"]; // 中邮总司暂时默认选中浙江省
    } else {
      ini_branchId = branch
        .filter(val => {
          return isZyAccount ? val.level != 0 : val;
        })
        .map(i => i.id);
      kbCode = branch.map(i => i.code && i.code);
      init_branch = branch;
    }
    reqYzPayload = {
      [isZyAccount ? "branch_id" : "code"]: isZyAccount
        ? [...ini_branchId].pop()
        : [...kbCode].pop(),
    };
    this.setState(
      {
        branch: init_branch,
        bracnhId: ini_branchId,
        reqYzPayload,
        isZyAccount,
        codeArr: kbCode,
      },
      () => {
        dispatch({
          type: "report/getYzList",
          payload: {
            ...reqYzPayload,
          },
        });
      }
    );
  }

  componentDidUpdate(prevProps, prevState) {
    const { isZyAccount, codeArr } = this.state;
    const { codeArr: oldCodeArr } = prevState;
    const { dispatch } = this.props;

    // 根据所选区域设置对应驿站列表
    if (!isEqual(oldCodeArr, codeArr) && !isZyAccount) {
      this.setState(
        {
          reqYzPayload: {
            code: [...codeArr].pop(),
          },
        },
        () => {
          dispatch({
            type: "report/getYzList",
            payload: {
              ...this.state.reqYzPayload,
            },
          });
        }
      );
    }
  }

  // 禁用日期过滤
  disabledDate = current => {
    return (
      current &&
      current >
        moment()
          .subtract(1, "days")
          .endOf("day")
    );
  };

  // 创建报表
  handleSubmit = e => {
    e.preventDefault();
    const {
      form,
      dispatch,
      report: { yzList },
    } = this.props;
    const { isZyAccount, codeArr } = this.state;
    let yzAllList = "";
    yzList.map(item => {
      yzAllList += `${item.cm_id},`;
    });
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      const { date, brand, dak, address, ...restData } = values;
      const start_date = date ? moment(date[0]).format(dateFormat) : "";
      const end_date = date ? moment(date[1]).format(dateFormat) : "";
      const dakAll = dak == "all" ? yzAllList.substring(0, yzAllList.length - 1) : dak;
      const payload = {
        brand,
        start_date,
        end_date,
        dak: dakAll,
        code: isZyAccount ? [...address].pop() : [...codeArr].pop(),
        ...restData,
      };
      if (JSON.stringify(payload) === this.prevReport) {
        message.error("该报表已生成，请点击“报表下载”查看");
        return;
      }
      dispatch({
        type: "report/getExportTask",
        payload,
        then: res => {
          if (res.code == 0) {
            this.prevReport = JSON.stringify(payload);
          }
        },
      });
    });
  };

  // 品牌下拉
  onGetOperatorList = visible => {
    if (!visible) return;
    const { dispatch } = this.props;
    dispatch({
      type: "list/getBrandsList",
      payload: {
        shop_id: "",
      },
    });
  };

  onPopupVisibleChange(visible) {
    const { isZyAccount } = this.state;
    const {
      form: { getFieldsValue },
      dispatch,
    } = this.props;
    const { address = [] } = getFieldsValue(["address"]);
    if (!visible && isZyAccount) {
      this.setState(
        {
          reqYzPayload: {
            branch_id: [...address].pop(),
          },
        },
        () => {
          dispatch({
            type: "report/getYzList",
            payload: {
              ...this.state.reqYzPayload,
            },
          });
        }
      );
    }
  }

  onAddressSelect(value, selectedOptions) {
    const { isZyAccount } = this.state;
    const {
      form: { setFieldsValue },
    } = this.props;
    setFieldsValue({
      dak: "all",
    });
    const codeArr = selectedOptions.map(val => {
      for (let i = 0; i < value.length; i++) {
        const id = value[i];
        if (id == val.id) {
          return val.code || "";
        }
      }
    });
    !isZyAccount &&
      this.setState({
        codeArr,
      });
  }

  render() {
    const { branch, bracnhId, reqYzPayload, isZyAccount } = this.state;
    const {
      form: { getFieldDecorator },
      submitting,
      operatoring,
      list,
    } = this.props;
    const dropList = (list && list.brandList) || [];
    const yesterday = moment().subtract(1, "days");
    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 8 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
    };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 16,
          offset: 8,
        },
      },
    };
    return (
      <div style={{ paddingTop: 30 }}>
        <Form {...formItemLayout}>
          <FormItem label="选择日期" extra="仅限选择昨日及昨日以前日期">
            {getFieldDecorator("date", {
              rules: [
                {
                  required: true,
                  message: "请选择日期",
                },
              ],
              initialValue: [yesterday, yesterday],
            })(
              <RangePicker
                style={{ width: 350 }}
                format={dateFormat}
                disabledDate={this.disabledDate}
              />
            )}
          </FormItem>
          <FormItem label="选择区域">
            {getFieldDecorator("address", {
              initialValue: bracnhId,
            })(
              <AddressCascader
                canChooseParent={!isZyAccount}
                onSelect={this.onAddressSelect.bind(this)}
                onPopupVisibleChange={this.onPopupVisibleChange.bind(this)}
                level={3}
                style={{ width: 350 }}
                placeholder="请选择区域"
                request
                branch={branch}
                changeOnSelect
              />
            )}
          </FormItem>
          <FormItem label="快递品牌">
            {getFieldDecorator("brand", {
              initialValue: "all",
            })(
              <Select
                onDropdownVisibleChange={this.onGetOperatorList}
                showSearch
                allowClear
                placeholder="全部品牌"
                style={{ width: "150px" }}
              >
                {operatoring ? (
                  <Option disabled value="loading">
                    <Spin />
                  </Option>
                ) : (
                  <Option key="all" value="all">
                    全部品牌
                  </Option>
                )}
                {dropList.map(({ brand_en, brand }) => (
                  <Option key={brand_en} value={brand_en}>
                    {brand}
                  </Option>
                ))}
              </Select>
            )}
          </FormItem>
          <FormItem label="选择驿站">
            {getFieldDecorator("dak", {
              initialValue: "all",
            })(<Yzs style={{ width: "150px" }} reqPayload={reqYzPayload} />)}
          </FormItem>
          <FormItem label="按出入库操作">
            {getFieldDecorator("operate", {
              initialValue: "in",
            })(<StandardSelect kkey="code" options={inoutTypes} />)}
          </FormItem>
          <FormItem {...tailFormItemLayout}>
            <Popconfirm title="确认根据当前筛选条件生成报表？" onConfirm={this.handleSubmit}>
              <Button loading={submitting} type="primary" icon="file-text">
                生成报表
              </Button>
            </Popconfirm>
          </FormItem>
        </Form>
      </div>
    );
  }
}

export default TemplateAdd;
